<template>
  <div class="register_container">
    <div class="register_box">
      <div style="font-weight: bold; font-size: 24px; text-align: center; margin-bottom: 30px">注 册</div>
      <div>
        <el-form :model="data.form" ref="ruleFormRef" :rules="rules">
          <el-form-item prop="username">
            <el-input  prefix-icon="User" v-model="data.form.username" placeholder="请输入用户名"/>
          </el-form-item>
          <el-form-item prop="password">
            <el-input show-password prefix-icon="Lock" v-model="data.form.password" placeholder="请输入密码"/>
          </el-form-item>
          <el-form-item prop="confirmPassword">
            <el-input show-password prefix-icon="Lock" v-model="data.form.confirmPassword" placeholder="请确认密码"/>
          </el-form-item>
        </el-form>
        <el-button style="width: 100%" type="primary" @click="register">注册</el-button>
      </div>
      <div style="font-size: 12px; margin-top: 30px; text-align: right">
        <a href="/login" ><span >前往登录</span></a>
      </div>
    </div>
  </div>

</template>

<script setup>

import {ref,reactive} from 'vue'
import {ElMessage} from "element-plus";
import request from "@/utils/request";
import router from "@/router";

const data = reactive({
  form : {}
})

const ruleFormRef = ref()

/**
 * 自定义校验规则
 * @param rule
 * @param value
 * @param callback
 */
const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('密码不能为空'))
  } else if (value !== data.form.password) {
    callback(new Error("两次密码输入不一致"))
  } else {
    callback()
  }
}

const rules = reactive({
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' }
  ],
  confirmPassword: [{ validator: validateConfirmPassword, trigger: 'blur' }],
})

const register = () => {
  ruleFormRef.value.validate((valid) => {
    if(valid){
      request.post("/register",data.form).then((res) => {
        if(res.code === '200'){
          ElMessage.success("注册成功")
          router.push("/login")
        }else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}
</script>

<style scoped>

.register_container {
  /** 项目图片*/
  background-image: url("@/assets/imgs/bg.png");
  /** 图片撑起整个元素*/
  background-size: cover;
  /** 布局方式： 弹性布局*/
  display: flex;
  /** 水平方向*/
  align-items: center;
  /** 垂直方向*/
  justify-content: center;
  /** 高度*/
  min-height: 100vh;
}

.register_box {
  /** 宽度 */
  width: 350px;
  /** 背景颜色 */
  background-color: #fff;
  /** 阴影效果 */
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  /** 内边距 */
  padding: 30px;
  /** 圆角 */
  border-radius: 15px;
}
</style>